//
//  XGL_PersonalPublishPhotoViewController.swift
//  XGamesLive
//
//  Created by ios on 2024/5/21.
//

import UIKit

class XGL_PersonalPublishPhotoViewController: UIViewController,CustomNavgationBar{
    lazy var hudView: XGL_CustomHudView = XGL_CustomHudView()
    var titleText: UITextField!
    var topicText: UITextField!
    var imagePickerView: ImagePickerView!
    var labelView: XGL_PersonalPublishLabelView!
    var imageUrls: [String] = []
    var publishTitle: String{
        return self.titleText.text ?? ""
    }
    var publishTopic: String{
        return self.topicText.text ?? ""
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.createCustomBackgroundView()
        self.createXglView()
        self.creatClearNavigationBar(title: "Post Photo")
    }
    

}

extension XGL_PersonalPublishPhotoViewController{
    @objc private func sendAction(){
        let alertView = XGL_PersonalPublishLiveAlertView()
        alertView.showAlertView {
            self.publishPhoto()
        }
        self.view.addSubview(alertView)
        alertView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
}

extension XGL_PersonalPublishPhotoViewController{
    private func publishPhoto(){
        guard self.publishTitle.isEmpty == false else {
            MXProgressHUD.hudWithText("Please enter Photo Title")
            return
        }
        guard self.topicText.isEmpty == false else {
            MXProgressHUD.hudWithText("Please select Topic")
            return
        }
        guard self.imagePickerView.pickImages.isEmpty == false else {
            MXProgressHUD.hudWithText("Please select Photo")
            return
        }
        self.hudView.backgroundColor = .clear
        self.hudView.hudView.startAnimation()
        self.view.addSubview(self.hudView)
        self.hudView.snp.makeConstraints { make in
            make.width.centerX.bottom.equalToSuperview()
            make.top.equalTo(PanNavibarH)
        }
        self.uploadImagesRequest { [weak self] in
            guard let `self` = self else { return }
            self.publishDataRequest()
        }
    }
}

extension XGL_PersonalPublishPhotoViewController{
    private func uploadImagesRequest(complete: (()->Void)? = nil){
        PanRequestManager<XGL_RequestBaseResponse<Response>,XGL_CustomRequestError>().request(CustomRequestAPI(requestAPI: .UploadImages(images: self.imagePickerView.pickImages))) { result in
            switch result{
            case .success(let response):
                if let arrays = response.resultArray{
                    let imageurls = arrays.compactMap({$0.wrappedValue as? String})
                    self.imageUrls = imageurls
                }
                if let block = complete {
                    block()
                }
                break
            default:
                break
            }
        }
    }
    
    private func publishDataRequest(){
        let data = PublishParamsData(data1: "2",data2: self.publishTitle,data3: self.imageUrls.joined(separator: ","),data4: "1",data5: self.publishTopic,data6: self.labelView.selectItems.joined(separator: ","))
        PanRequestManager<XGL_RequestBaseResponse<Response>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .PublishData(data: data))) { result in
            self.hudView.dismiss()
            switch result{
            case .success(let response):
                XGL_Notice.default.post(name: XGL_Notification.publish.notificationName, object: nil)
                MXProgressHUD.hudWithText("Successful publication") {
                    self.navigationController?.popViewController()
                }
                break
            default:
                break
            }
        }
    }
}

extension XGL_PersonalPublishPhotoViewController: UITextFieldDelegate{
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        if textField == self.topicText{
            self.showTopicPickerView()
            return false
        }
        return true
    }
}

extension XGL_PersonalPublishPhotoViewController{
    private func showTopicPickerView(){
        let keyArr = ["Computer Games","Host Games","Handheld Games"]
        let dataPicker = MXDataPicker()
        dataPicker.cancleTitle = "Cancel"
        dataPicker.sureTitle = "Sure"
        dataPicker.pickerType = .nomal
        dataPicker.dataType = .peers
        dataPicker.pickerData = MXDataPicker.DataPickerModel(firstLevelArr: [], secondLevelArr: [], peersArr: [keyArr])
        dataPicker.backgroundColor = UIColor.black.withAlphaComponent(0.30)
        dataPicker.showDataPicker(pickerTitle: "")
        dataPicker.selectData { result in
            if let selectItem = result.peersValue.first{
                self.topicText.text = selectItem.value
            }
        }
        self.view.addSubview(dataPicker)
        dataPicker.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
}

extension XGL_PersonalPublishPhotoViewController{
    private func createXglView(){
        let scrollView = UIScrollView()
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        self.view.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.width.centerX.bottom.equalToSuperview()
            make.top.equalTo(PanNavibarH)
        }
        let contentView = UIView()
        scrollView.addSubview(contentView)
        contentView.snp.makeConstraints { (make) in
            make.edges.equalTo(scrollView)
            make.width.equalTo(scrollView)
        }
        self.titleText = UITextField().then({ make in
            make.textColor = UIColor.white
            make.font = UIFont.pingfangSC_Regular(fontSize: 16.0)
            make.attributedPlaceholder = "Enter here".attributesColor(UIColor.hexColor("#A2A2A2"),UIFont.pingfangSC_Regular(fontSize: 16.0))
        })
        let titleView = XGLPublishUIManager.creatInputTextItemView(title: "Photo Title", inputText: self.titleText)
        self.topicText = UITextField().then({ make in
            make.textColor = UIColor.white
            make.font = UIFont.pingfangSC_Regular(fontSize: 16.0)
            make.attributedPlaceholder = "Click to select".attributesColor(UIColor.hexColor("#A2A2A2"),UIFont.pingfangSC_Regular(fontSize: 16.0))
            make.delegate = self
        })
        let topicView = XGLPublishUIManager.creatInputTextItemView(title: "Topic", inputText: self.topicText, rightItem: UIImageView(image: imageWithName("icon_xgl_down")))
        self.imagePickerView = ImagePickerView().then({ make in
            make.defaultUploadIcon = XGLPublishUIManager.createUploadIocn()
            make.deleteIcon = imageWithName("icon_image_pick_delete")
            make.imageNumSingleLine = 2
            make.maxImageSelectCount = 6
            make.imageRotio = 163.0 / 117.0
            make.imageSpace = 20.0
            make.pickerType = .image
        })
        let pickerView = XGLPublishUIManager.createCommonItemView(title: "Photo", commonView: self.imagePickerView)
        self.labelView = XGL_PersonalPublishLabelView()
        self.labelView.labels = [PublishLabelData(title: "#Happy",isSelected: true),PublishLabelData(title: "#Sad"),PublishLabelData(title: "#Distressed")]
        let labelView = XGLPublishUIManager.createCommonItemView(title: "Label", commonView: self.labelView)
        let sendButton = UIButton().then { make in
            make.setTitle("Send", for: .normal)
            make.setTitleColor(UIColor.hexColor("#191A1D"), for: .normal)
            make.titleLabel?.font = UIFont.pingfangSC_Regular(fontSize: 18.0)
            make.backgroundColor = UIColor.hexColor("#80FFE6")
            make.layerCornerRadius = 24.0
            make.addTarget(self, action: #selector(self.sendAction), for: .touchUpInside)
        }
        contentView.addSubviews([titleView,topicView,pickerView,labelView,sendButton])
        titleView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(32.0)
            make.left.equalTo(15.0)
        }
        topicView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.left.equalTo(15.0)
            make.top.equalTo(titleView.snp.bottom).offset(25.0)
        }
        pickerView.snp.makeConstraints { make in
            make.centerX.width.equalToSuperview()
            make.top.equalTo(topicView.snp.bottom).offset(25.0)
        }
        labelView.snp.makeConstraints { make in
            make.centerX.width.equalToSuperview()
            make.top.equalTo(pickerView.snp.bottom).offset(25.0)
        }
        sendButton.snp.makeConstraints { make in
            make.left.equalTo(15.0)
            make.centerX.equalToSuperview()
            make.top.equalTo(labelView.snp.bottom).offset(conversionWithScrennWidth(value: 72.0))
            make.height.equalTo(48.0)
        }
        contentView.snp.makeConstraints { make in
            make.bottom.equalTo(sendButton.snp.bottom).offset(BottomHeight + 42.0)
        }
    }
}
